
package cartagows.wsframework.wssecurity.core;

import org.apache.axiom.soap.SOAP11Constants;
import org.apache.ws.security.SOAPConstants;
import org.apache.ws.security.WSConstants;
import org.apache.ws.security.util.WSSecurityUtil;
import org.apache.xml.security.utils.EncryptionConstants;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.ArrayList;

public class ValidatorData {

    private MessageData md;
    ArrayList encryptedDataRefIds = new ArrayList();
    private String bodyEncrDataId;
    
    public ValidatorData(MessageData md) {
        this.md = md;
        this.extractEncryptedPartInformation();
    }
    
    private void extractEncryptedPartInformation() {
        Element start = md.getDocument().getDocumentElement();
        if(start != null) {
            extractEncryptedPartInformation(start);
        }
        
    }
    
    private void extractEncryptedPartInformation(Element parent) {

        NodeList childNodes = parent.getChildNodes();
        Node node;
		SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(md.getDocument().getDocumentElement());
        for (int i = 0; i < childNodes.getLength(); i++) {
            node = childNodes.item(i);
            if (node instanceof Element) {
                Element elem = (Element) node;
                if (elem.getNamespaceURI() != null 
                        && elem.getNamespaceURI().equals(WSConstants.ENC_NS)
                        && elem.getLocalName().equals(
                                EncryptionConstants._TAG_ENCRYPTEDDATA)) {
                    if (parent.getLocalName().equals(
                                    SOAP11Constants.BODY_LOCAL_NAME)
                            && parent.getNamespaceURI().equals(
                                    soapConstants.getEnvelopeURI())) {
                        this.bodyEncrDataId = elem.getAttribute("Id");
                    } else {
                        encryptedDataRefIds.add(elem.getAttribute("Id"));
                    }
                    break;
                } else {
                    extractEncryptedPartInformation(elem);
                }
            }
        }
    }

    public ArrayList getEncryptedDataRefIds() {
        return encryptedDataRefIds;
    }

    public MessageData getMessageData() {
        return md;
    }

    public String getBodyEncrDataId() {
        return bodyEncrDataId;
    }
    
}
